using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using Voodoo.Sauce.Internal.CrossPromo.Models;
using Voodoo.Sauce.Internal.CrossPromo.Utils;

namespace Voodoo.Sauce.Internal.CrossPromo.Canvas
{
	public class VideoManager
	{
		private readonly RenderTexture _renderTexture;

		public RawImage Content { get; }

		public VideoPlayer VideoPlayer { get; }

		public VideoManager(VideoPlayer video, RawImage content)
		{
			VideoPlayer = video;
			Content = content;
			Content.enabled = false;
			VideoPlayer.prepareCompleted += OnVideoComplete;
			_renderTexture = new RenderTexture(0, 0, 24);
		}

		public static AssetModel ChooseVideo()
		{
			return null;
		}

		public void PrepareVideo(AssetModel asset)
		{
			if (_renderTexture.IsCreated())
			{
				ReleaseTexture();
			}
			if (!CacheManager.IsFileExist(asset.file_path))
			{
				throw new Exception("Can not read the file because it doesn't exist");
			}
			VideoPlayer.url = CacheManager.Path + asset.file_path;
			VideoPlayer.Prepare();
		}

		public void StopVideo()
		{
			Content.enabled = false;
			VideoPlayer.Stop();
		}

		private void ReleaseTexture()
		{
			_renderTexture.Release();
			_renderTexture.DiscardContents();
		}

		private void OnVideoComplete(VideoPlayer source)
		{
			Texture texture = source.texture;
			int width = texture.width;
			int height = texture.height;
			if (!_renderTexture.IsCreated())
			{
				_renderTexture.width = width;
				_renderTexture.height = height;
			}
			_renderTexture.Create();
			VideoPlayer.targetTexture = _renderTexture;
			Content.texture = _renderTexture;
			Content.enabled = true;
			ReleaseTexture();
		}
	}
}
